<template>
  <div class="registration-container">
    <van-nav-bar
      title="预约挂号"
      left-arrow
      @click-left="onClickLeft"
    />

    <div class="form-wrapper">
      <!-- 科室选择 -->
      <van-cell-group inset class="form-group">
        <van-field
          v-model="formData.departmentName"
          is-link
          readonly
          label="选择科室"
          placeholder="请选择科室"
          @click="showDepartmentPicker = true"
        />
      </van-cell-group>

      <!-- 排班信息展示 -->
      <van-cell-group inset class="form-group">
      <div v-if="formData.departmentId" class="schedule-wrapper">
        <van-tabs v-model="activeDate" @click-tab="onClickTab">
          <van-tab v-for="date in availableDates" :key="date.value" :title="date.label" :name="date.value" >
            <div class="doctor-schedules">
              <div v-for="doctor in doctorSchedules" :key="doctor.id" class="doctor-item">
                <div class="doctor-info">
                  <span class="doctor-name">{{ doctor.name }}</span>
                  <span class="doctor-title">{{ doctor.title }}</span>
                </div>
                <div class="time-slots">
                  <van-button
                    v-for="slot in doctor.timeSlots"
                    :key="slot.time"
                    size="small"
                    :type="isSelectedSlot(doctor, slot) ? 'primary' : 'default'"
                    :disabled="slot.remaining === 0"
                    @click="selectTimeSlot(doctor, slot)"
                  >
                    {{ slot.time }}
                    <span class="remaining">(剩余{{ slot.remaining }})</span>
                  </van-button>
                </div>
              </div>
            </div>
          </van-tab>
        </van-tabs>
      </div>
      </van-cell-group>

      <!-- 挂号类型 -->
      <van-cell-group inset class="form-group">
        <van-cell title="挂号类型">
          <template #value>
            <van-radio-group v-model="formData.type" direction="horizontal">
              <van-radio :name="1">普通号(￥20)</van-radio>
              <van-radio :name="2">专家号(￥50)</van-radio>
              <van-radio :name="3">急诊号(￥80)</van-radio>
            </van-radio-group>
          </template>
        </van-cell>
      </van-cell-group>

      <!-- 备注信息 -->
      <van-cell-group inset class="form-group">
        <van-field
          v-model="formData.remark"
          label="备注信息"
          type="textarea"
          placeholder="请输入备注信息（选填）"
          rows="3"
          maxlength="200"
          show-word-limit
        />
      </van-cell-group>
    </div>

    <!-- 科室选择弹窗 -->
    <van-popup v-model:show="showDepartmentPicker" round position="bottom">
      <van-cascader
        v-model="cascaderValue"
        title="请选择科室"
        :options="departmentOptions"
        @close="showDepartmentPicker = false"
        @finish="onDepartmentFinish"
      />
    </van-popup>

    <!-- 底部提交按钮 -->
    <div class="submit-btn">
      <van-button 
        type="primary" 
        block 
        @click="handleSubmit" 
        :loading="submitting"
        :disabled="!isValidSelection"
      >
        确认预约 (￥{{ registrationFee }})
      </van-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted ,watch} from 'vue'
import { showToast } from 'vant'
import { useRouter } from 'vue-router'
import { getDepartmentTree, getDoctorSchedules, makeAppointment } from '../api'
import dayjs from 'dayjs'

const router = useRouter()
const submitting = ref(false)

// 表单数据
const formData = ref({
  departmentId: '',
  departmentName: '',
  doctorId: '',
  doctorName: '',
  appointmentDate: '',
  appointmentTime: '',
  type: 1,
  fee: 20,
  remark: '',
  scheduleId: ''
})

// 科室选择相关
const showDepartmentPicker = ref(false)
const cascaderValue = ref('')
const departmentOptions = ref([])

// 排班相关
const activeDate = ref('')
const availableDates = ref([])
const doctorSchedules = ref([])
const selectedSlot = ref(null)

// 生成未来30天的日期选项
const generateDates = () => {
  const dates = []
  const today = dayjs()
  
  for (let i = 0; i < 30; i++) {
    const date = today.add(i, 'day')
    dates.push({
      label: date.format('MM-DD'),
      value: date.format('YYYY-MM-DD')
    })
  }
  
  availableDates.value = dates
  activeDate.value = dates[0].value
}

// 加载排班信息
const loadSchedules = async (date) => {
  if (!formData.value.departmentId) return
  
  try {
    const res = await getDoctorSchedules({
      departmentId: formData.value.departmentId,
      date: date
    })
    
    if (res.code === 200) {
      doctorSchedules.value = res.data.map(schedule => ({
        id: schedule.doctorId,
        name: schedule.doctorName,
        title: schedule.doctorTitle,
        timeSlots: schedule.timeSlots.map(slot => ({
          time: slot.time,
          remaining: slot.remainingQuota,
          scheduleId: slot.scheduleId
        }))
      }))
    }
  } catch (error) {
    console.error('获取排班信息失败：', error)
    showToast('获取排班信息失败')
  }
}

// 选择时间段
const selectTimeSlot = (doctor, slot) => {
  selectedSlot.value = {
    doctorId: doctor.id,
    doctorName: doctor.name,
    scheduleId: slot.scheduleId,
    time: slot.time,
    date: activeDate.value
  }
  
  formData.value.doctorId = doctor.id
  formData.value.doctorName = doctor.name
  formData.value.appointmentDate = activeDate.value
  formData.value.appointmentTime = slot.time
  formData.value.scheduleId = slot.scheduleId
}

// 判断是否是选中的时间段
const isSelectedSlot = (doctor, slot) => {
  return selectedSlot.value &&
         selectedSlot.value.doctorId === doctor.id &&
         selectedSlot.value.time === slot.time &&
         selectedSlot.value.date === activeDate.value
}

// 科室选择完成
const onDepartmentFinish = ({ selectedOptions }) => {
  const [mainDept, subDept] = selectedOptions
  formData.value.departmentId = subDept.value
  formData.value.departmentName = `${mainDept.text} - ${subDept.text}`
  showDepartmentPicker.value = false
  
  // 重置选择
  selectedSlot.value = null
  formData.value.doctorId = ''
  formData.value.doctorName = ''
  formData.value.appointmentDate = ''
  formData.value.appointmentTime = ''
  
  // 加载排班信息
  loadSchedules(activeDate.value)
}

// 监听日期切换
watch(activeDate, (newDate) => {
  if (formData.value.departmentId) {
    loadSchedules(newDate)
    // 重置选中状态
    selectedSlot.value = null
    formData.value.doctorId = ''
    formData.value.doctorName = ''
    formData.value.appointmentTime = ''
  }
})

// 挂号费用计算
const registrationFee = computed(() => {
  const feeMap = {
    1: 20,  // 普通号
    2: 50,  // 专家号
    3: 80   // 急诊号
  }
  return feeMap[formData.value.type] || 0
})

// 判断是否可以提交
const isValidSelection = computed(() => {
  return formData.value.departmentId &&
         formData.value.doctorId &&
         formData.value.appointmentDate &&
         formData.value.appointmentTime &&
         formData.value.scheduleId
})

// 提交预约
const handleSubmit = async () => {
  if (!isValidSelection.value) {
    showToast('请选择就诊科室、医生和时间')
    return
  }

  if (!formData.value.scheduleId) {
    showToast('预约信息不完整，请重新选择')
    return
  }

  try {
    submitting.value = true
    formData.value.fee = registrationFee.value
    
    const res = await makeAppointment(formData.value)
    if (res.code === 200) {
      showToast('预约成功')
      router.push('/my-registrations')
    } else {
      showToast(res.message || '预约失败')
    }
  } catch (error) {
    console.error('预约失败：', error)
    showToast('预约失败')
  } finally {
    submitting.value = false
  }
}

// 返回上一页
const onClickLeft = () => router.back()

// 加载科室树
const loadDepartmentTree = async () => {
  try {
    const res = await getDepartmentTree()
    if (res.code === 200) {
      departmentOptions.value = res.data.map(dept => ({
        text: dept.name,
        value: dept.id,
        children: dept.children?.map(child => ({
          text: child.name,
          value: child.id,
          disabled: child.status === 0
        }))
      }))
    }
  } catch (error) {
    console.error('获取科室列表失败：', error)
    showToast('获取科室列表失败')
  }
}

const onClickTab = (item) => {
  console.log(item)
  activeDate.value = item.name
  loadSchedules(item.name)
}

// 初始化
onMounted(() => {
  generateDates()
  loadDepartmentTree()
})
</script>

<style lang="scss" scoped>
.registration-container {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-bottom: 80px;

  :deep(.van-nav-bar) {
    background-color: #fff;
  }
}

.form-wrapper {
  padding: 16px;
}

.form-group {
  margin-bottom: 12px;
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;

  .van-cell {
    padding: 16px;
  }
}

// 日期选择样式
.schedule-wrapper {
  margin: 12px 0;
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;

  :deep(.van-tabs) {
    .van-tabs__wrap {
      height: 44px;
      padding: 0 24px;  // 为左右箭头留出空间

      &::before {
        content: '';
        position: absolute;
        left: 0;
        width: 24px;
        height: 100%;
        background: linear-gradient(to right, #fff, rgba(255, 255, 255, 0));
        z-index: 1;
      }

      &::after {
        content: '';
        position: absolute;
        right: 0;
        width: 24px;
        height: 100%;
        background: linear-gradient(to left, #fff, rgba(255, 255, 255, 0));
        z-index: 1;
      }
    }

    .van-tabs__nav {
      background-color: #fff;
    }

    .van-tab {
      flex: 0 0 auto;
      padding: 0 16px;
      font-size: 14px;
      
      &--active {
        color: var(--van-primary-color);
        font-weight: 500;
      }
    }
  }
}

.doctor-schedules {
  padding: 16px;
}

.doctor-item {
  margin-bottom: 20px;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.doctor-info {
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  
  .doctor-name {
    font-size: 16px;
    font-weight: 500;
    margin-right: 8px;
    color: #323233;
  }
  
  .doctor-title {
    font-size: 14px;
    color: #969799;
  }
}

.time-slots {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  gap: 8px;
  
  .van-button {
    width: 100%;
    height: 36px;
    font-size: 14px;
    border-radius: 4px;
    
    &--disabled {
      opacity: 0.6;
    }
    
    .remaining {
      font-size: 12px;
      margin-left: 4px;
      color: var(--van-gray-6);
    }
  }
}

// 挂号类型样式
:deep(.van-radio-group) {
  display: flex;
  gap: 16px;
  
  .van-radio {
    margin: 0;
  }
}

// 备注框样式
:deep(.van-field__word-limit) {
  margin-top: 4px;
  color: var(--van-gray-6);
}

// 底部按钮样式
.submit-btn {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 16px;
  background-color: #fff;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.06);

  .van-button {
    height: 44px;
    font-size: 16px;
    border-radius: 22px;
  }
}
</style> 